<template>
	<div class="body">
		<div class="form">
			<van-cell title="选择日期区间" :value="date" @click="show = true" />
			<van-divider />
			<van-calendar v-model:show="show" type="range" @confirm="onConfirm" />
			<van-cell-group inset>
				<!-- 输入任意文本 -->
				<van-field v-model="form.s" label="s" />
				<van-divider />

				<van-field v-model="form.t" label="t" />
				<van-divider />
				<van-field v-model="form.year" label="year" />
				<van-divider />
			</van-cell-group>
		</div>
		<div class="btns">
			<van-button type="success" style="width: 50vw" @click="createUrl">保存</van-button>
		</div>
	</div>
</template>
<script setup>
	import { ref } from 'vue'
	import moment from 'moment'

	import { showToast } from 'vant'

	const date = ref('')
	const show = ref(false)

	const form = ref({
		s: '',
		t: '',
		et: '',
		year: ''
	})

	const formatDate = (date) => `${date.getMonth() + 1}/${date.getDate()}`
	const onConfirm = (values) => {
		const [start, end] = values
		show.value = false
		form.value.t = moment(start).unix()
		form.value.et = moment(end).unix()
		form.value.year = start.getFullYear()
		date.value = `${form.value.t} - ${form.value.et}`
		console.log(form.value)
	}

	const createUrl = () => {
		const url = `https://xiaokefu.net.cn/#/official/OfficialQrPublic/MobileQrList?s=${form.value.s}&t=${form.value.t}&et=${form.value.et}&year=${form.value.year}`
		if (navigator.clipboard && navigator.clipboard.writeText) {
			// 如果支持 navigator.clipboard API
			navigator.clipboard
				.writeText(url)
				.then(() => {
					showToast('复制成功')
				})
				.catch((err) => {
					showToast('复制失败: ' + err)
					// 如果 clipboard API 出现错误，使用回退方案
					fallbackCopyText(url)
				})
		} else {
			// 不支持 clipboard API，使用回退方案
			fallbackCopyText()
		}
	}
	const fallbackCopyText = (text) => {
		const textarea = document.createElement('textarea')
		textarea.value = text
		textarea.style.position = 'fixed' // 防止页面跳动
		document.body.appendChild(textarea)
		textarea.select()
		try {
			const successful = document.execCommand('copy')
			const msg = successful ? '复制成功' : '复制失败'
			showToast(msg)
		} catch (err) {
			showToast('复制失败: ' + err)
		}
		document.body.removeChild(textarea)
	}
</script>

<style scoped lang="less">
	.body {
		width: 100vw;
		height: 100vh;
		padding: 20px;
		box-sizing: border-box;
		background: rgba(242, 244, 245, 1);
		.form {
			background: #fff;
		}
		.btns {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 20vh;
		}
	}
</style>
